package cn.lili.modules.order.order.serviceimpl;

import cn.hutool.json.JSONUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.context.UserContext;
import cn.lili.modules.member.client.UserClient;
import cn.lili.modules.member.client.VipConfigClient;
import cn.lili.modules.member.entity.dos.User;
import cn.lili.modules.order.order.entity.dos.AuditOrder;
import cn.lili.modules.order.order.entity.dos.VipOrder;
import cn.lili.modules.order.order.mapper.AuditOrderMapper;
import cn.lili.modules.order.order.mapper.VipOrderMapper;
import cn.lili.modules.order.order.service.AuditOrderService;
import cn.lili.modules.order.order.service.VipOrderService;
import cn.lili.modules.system.client.SettingClient;
import cn.lili.modules.system.entity.dos.LiVipConfig;
import cn.lili.modules.system.entity.dos.Setting;
import cn.lili.modules.system.entity.dto.UrbanSubstationAuditSetting;
import cn.lili.modules.urbansubstation.client.UrbanSubstationClient;
import cn.lili.modules.urbansubstation.entity.dos.UrbanSubstation;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
@RequiredArgsConstructor
public class AuditOrderServiceImpl extends ServiceImpl<AuditOrderMapper, AuditOrder>
        implements AuditOrderService {

    @Resource
    private SettingClient settingClient;

    private final UserClient userClient;

    @Override
    public AuditOrder createOrder (Double price) {
        Setting setting = settingClient.get("URBANSUBSTATION_AUDIT_SETTING");
        UrbanSubstationAuditSetting urbanSubstationAuditSetting = JSONUtil.toBean(setting.getSettingValue(), UrbanSubstationAuditSetting.class);
        if (!Double.valueOf(String.valueOf(urbanSubstationAuditSetting.getAuditMoney())).equals(price)) {
            throw new ServiceException("审核价格不正确，请重新购买");
        }
        User user = userClient.getById(UserContext.getCurrentId());
        AuditOrder auditOrder = new AuditOrder(price, user.getUrbanSubstationId());
        save(auditOrder);
        return auditOrder;
    }

    @Override
    public AuditOrder getBySn(String sn) {
        LambdaQueryWrapper<AuditOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AuditOrder::getSn, sn);
        queryWrapper.last("limit 1");
        return this.baseMapper.selectOne(queryWrapper);
    }
}
